package com.webwork.lims.orders.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;
import com.webwork.lims.common.controller.SuperCtrl;
import com.webwork.lims.common.dataobject.CtrlerAndTime;
import com.webwork.lims.orders.dataobject.Order;
import com.webwork.lims.orders.dataobject.OrderStatus;
import com.webwork.lims.orders.service.OrderService;
import com.webwork.lims.system.dataobject.Role;
import com.webwork.lims.system.dataobject.User;
import com.webwork.lims.transport.dataobject.Zone;
import com.webwork.lims.transport.service.ZoneService;
import com.webwork.lims.util.DateFormat;
import com.webwork.lims.util.Paging;
import com.webwork.lims.util.StrManager;
import com.webwork.lims.warehouse.dataobject.OutcomeOrder;
import com.webwork.lims.warehouse.dataobject.OutcomeType;
import com.webwork.lims.warehouse.dataobject.WarehouseStatus;
import com.webwork.lims.warehouse.service.OutcomeService;

@Controller
@RequestMapping(value = "/order")
public class OrderController extends SuperCtrl {

	@Autowired
	private OrderService orderSve;
	
	@Autowired
	private OutcomeService outcomeSve;
	
	@Autowired
	private ZoneService zoneSve;
	
	@RequestMapping(value = "/createOrder")
	public String createOrder() {
		return "createOrder";
	}
	
	@RequestMapping(value = "/verifyOrder")
	public String verifyOrder() {
		return "verifyOrder";
	}
	
	@RequestMapping(value = "/confirmOrder")
	public String confirmOrder() {
		return "confirmOrder";
	}

	@RequestMapping(value = "/queryOrder")
	@Override
	public String mainPage() {
		return "queryOrder";
	}
	
	@RequestMapping(value = "queryOrdersList")
	@ResponseBody
	public ResponseEntity<String> queryList(
			@RequestParam(value = "page") int page,
			@RequestParam(value = "rows") int rows,
			@RequestParam(required = false, value = "cmd") String cmdStr,
			HttpServletRequest request)
					throws Exception {
		User user = (User) request.getSession(true).getAttribute("user");
		Order queryObj = new Order();
		if (!StrManager.isEmpty(cmdStr)) {
			queryObj = new Gson().fromJson(cmdStr, Order.class);
			queryObj.setStatus(queryObj.getStatusCode());
		}
		if (user.getRole() == Role.DELIVERY) {
			Zone zoneQuery = new Zone();
			zoneQuery.setDelivery(user.getUserId());
			List<Zone> zones = zoneSve.query(zoneQuery);
			Zone thisZone = null;
			if (zones != null && zones.size() > 0) {
				thisZone = zones.get(0);
				queryObj.setZoneCode(thisZone.getZoneCode());
			}
		}
		HttpHeaders responseHeaders = new HttpHeaders();
		responseHeaders.add("Content-Type", "text/html; charset=utf-8");
		Map<String, Object> ret = new HashMap<String, Object>();
	
		ret.put("total", orderSve.count(queryObj));
		ret.put("rows", orderSve.query(queryObj, new Paging(page, rows)));
		
		return new ResponseEntity<String>(new Gson().toJson(ret).toString(), responseHeaders, HttpStatus.CREATED);
	}
	
	@RequestMapping(value = "getOrder")
	@ResponseBody
	public ResponseEntity<String> getOrder(@RequestParam("orderId") String orderId) {
		HttpHeaders responseHeaders = new HttpHeaders();
		responseHeaders.add("Content-Type", "text/html; charset=utf-8");
		Order order = orderSve.get(orderId);
		return new ResponseEntity<String>(new Gson().toJson(order).toString(), responseHeaders, HttpStatus.CREATED);
	}
	
	@RequestMapping(value="loadStatus")
	@ResponseBody
	public ResponseEntity<String> loadStatus() {
		HttpHeaders responseHeaders = new HttpHeaders();
		responseHeaders.add("Content-Type", "text/html; charset=utf-8");
		OrderStatus[] status = OrderStatus.useableValues();
		List<Object> ret = new ArrayList<Object>();
		for (OrderStatus o : status) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("value", o.getCode());
			map.put("name", o.getCode() + " - " + o.getMsg());
			ret.add(map);
		}
		return new ResponseEntity<String>(new Gson().toJson(ret).toString(), responseHeaders, HttpStatus.CREATED);
	}
	
	@RequestMapping(value = "addOrder")
	@ResponseBody
	public String addOrder(@RequestParam("jsonObj") String jsonObj, HttpServletRequest request) {
		User user = (User) request.getSession(true).getAttribute("user");
		HttpHeaders responseHeaders = new HttpHeaders();
		responseHeaders.add("Content-Type", "text/html; charset=utf-8");
		Order order = new Gson().fromJson(jsonObj, Order.class);
		order.setOrderId("OR" + DateFormat.NUMBER.format(new Date()));
		order.setStatus(OrderStatus.WAITING);
		order.setCreate(new CtrlerAndTime(user.getUserName(), new Date()));
		orderSve.save(order);
		return SUCCESS;
	}
	
	@RequestMapping(value = "editOrder")
	@ResponseBody
	public String editOrder(@RequestParam("jsonObj") String jsonObj) {
		HttpHeaders responseHeaders = new HttpHeaders();
		responseHeaders.add("Content-Type", "text/html; charset=utf-8");
		Order o = new Gson().fromJson(jsonObj, Order.class);
		Order order = orderSve.get(o.getOrderId());
		if (order == null) {
			return NOT_EXIST;
		}
		order.setSku(o.getSku());
		order.setAmount(o.getAmount());
		order.setZoneCode(o.getZoneCode());
		order.setAddress(o.getAddress());
		order.setReceiver(o.getReceiver());
		order.setPhone(o.getPhone());
		orderSve.save(order);
		return SUCCESS;
	}
	
	@RequestMapping(value = "verify")
	@ResponseBody
	public String verifyOrder(@RequestParam("orderId") String orderId, HttpServletRequest request) {
		User user = (User) request.getSession(true).getAttribute("user");
		HttpHeaders responseHeaders = new HttpHeaders();
		responseHeaders.add("Content-Type", "text/html; charset=utf-8");
		Order order = orderSve.get(orderId);
		if (order == null) {
			return FAIL;
		}
		order.setStatus(OrderStatus.VERIFIED);
		order.setVerify(new CtrlerAndTime(user.getUserName(), new Date()));
		orderSve.save(order);
		
		//生成出库单
		OutcomeOrder outcome = new OutcomeOrder();
		outcome.setOutcomeId("OC" + DateFormat.NUMBER.format(new Date()));
		outcome.setType(OutcomeType.DELIVERY);
		outcome.setStatus(WarehouseStatus.CREATED);
		outcome.setSku(order.getSku());
		outcome.setAmount(order.getAmount());
		outcome.setCreate(order.getVerify());
		outcome.setOrderId(orderId);
		outcomeSve.save(outcome);
		
		return SUCCESS;
	}
	
	@RequestMapping(value = "cancel")
	@ResponseBody
	public String cancelOrder(@RequestParam("orderId") String orderId, HttpServletRequest request) {
		User user = (User) request.getSession(true).getAttribute("user");
		HttpHeaders responseHeaders = new HttpHeaders();
		responseHeaders.add("Content-Type", "text/html; charset=utf-8");
		Order order = orderSve.get(orderId);
		if (order == null) {
			return FAIL;
		}
		order.setStatus(OrderStatus.CANCEL);
		order.setComplete(new CtrlerAndTime(user.getUserName(), new Date()));
		orderSve.save(order);
		return SUCCESS;
	}
	
	@RequestMapping(value = "confirm")
	@ResponseBody
	public String confirmOrder(@RequestParam("orderId") String orderId, HttpServletRequest request) {
		User user = (User) request.getSession(true).getAttribute("user");
		HttpHeaders responseHeaders = new HttpHeaders();
		responseHeaders.add("Content-Type", "text/html; charset=utf-8");
		Order order = orderSve.get(orderId);
		if (order == null) {
			return FAIL;
		}
		order.setStatus(OrderStatus.COMPLETE);
		order.setComplete(new CtrlerAndTime(user.getUserName(), new Date()));
		orderSve.save(order);
		return SUCCESS;
	}
	
	@RequestMapping(value = "getOrderByTransID")
	@ResponseBody
	public ResponseEntity<String> getOrderByTransID(@RequestParam("transId") String transId) {
		HttpHeaders responseHeaders = new HttpHeaders();
		responseHeaders.add("Content-Type", "text/html; charset=utf-8");
		List<Order> order = orderSve.getByTransId(transId);
		return new ResponseEntity<String>(new Gson().toJson(order).toString(), responseHeaders, HttpStatus.CREATED);
	}
	
}
